/**
 * Created by zhanglihe on 15/11/10.
 */
require.config(require_config);

define([
    'jquery',
    'common',
    'ready',
    'template',
    'model',
    'dialog',
    'ckeditor'
], function ($, common, ready, template, Model, dialog, ckeditor) {

    var id = getUrlPath(4);

    var index = function () {
        this.init();
    };

    index.prototype = {
        init: function () {
            var _this = this;
            _this.spec_key = [];//存储当前所有的规格参数

            //分类
            $.ajax({
                url: _global.url.api + 'site_categorys',
                type: 'get',
                async: false,
                success: function (res) {
                    if (res.code == 0) {
                        _this.set('category', res.data);
                    }
                }
            });
            //运费模板
            $.ajax({
                url: _global.url.api + 'shipping',
                type: 'get',
                async: false,
                success: function (res) {
                    if (res.code == 0) {
                        _this.set('shipping', res.data);
                    }
                }
            });

            this.fetch();
            this.event();
            _this.rebate_amount();
        },
        formData: {},
        fetch: function () {
            var _this = this;

            //$('#main-view').html(template('add-tpl', {shipping: this.shipping}));

            this.model = new Model({
                url: _global.url.api + 'jd_goods/' + id,
                sync: function () {
                    //遍历catalog,指定selected项
                    var model = this;

                    $('#main-view').html(template('add-tpl', {shipping: _this.shipping, goods: this.data}));
                    this.renderCate();
                },
                //输出分类
                renderCate: function () {
                    _this.model.data.cate_ids = [];
                    $.each(this.data.category, function () {
                        _this.model.data.cate_ids.push(this.id);
                        _this.cate.add(this.id, this.name);
                    });
                }
            });
            this.model.fetch();
        },
        set: function ($k, $v) {
            this[$k] = $v;
        },
        rebate_amount: function () {
            var rebate = $('input[name="rebate"]').val();
            var price  = $('input[name="price"]').val();
            var amount = (rebate*price/100).toFixed(2);
            $('#rebate_amount').html(amount);
        },
        event: function () {
            var _this = this;

            $('input,select,textarea').on('change', function (e) {
                _this.change(e);
            });

            //保存事件
            var ajaxPending = false;
            $('#btn-save').on('click', function (e) {
                if (ajaxPending) return;
                e.preventDefault();
                //分类
                var cate_ids = _this.cate.get();
                if (cate_ids.sort().toString() !== _this.model.data.cate_ids.sort().toString()) {
                    _this.formData.cate_ids = cate_ids;
                }
                //相册
                //_this.formData.album = _this.album.get();
                //商品详情
                _this.formData.intro = $('[name="intro"]').val();

                //是否单品包邮
                _this.model.data._is_free_shipping_ = $('input[name="_is_free_shipping_"]:checked').val();
                ajaxPending = true;
                new Model({
                    url: _global.url.api + 'jd_goods/' + id,
                    data: _this.formData,
                    valid_config: {
                        name: 'required',
                        cate_ids: function (model, val) {
                            return !( model.get_data('cate_ids') !== undefined && val.length == 0);
                        },
                        //sn: 'required',
                        weight: 'number',
                        rebate: 'number',
                        rebate1: 'number',
                        rebate2: 'number',
                        price: 'required',
                        shipping_template: 'number',
                        stock: function (model, val) {
                            return val >= 0;
                        }
                    },
                    success: function () {
                        _this.callback('/admin/jd_goods');
                        ajaxPending = false;
                    }
                }).put();
            });

            //计算总分成
            $('#rebate').on('keyup',function(){
                _this.rebate_amount();
            })
            //选择分类
            $('#btn-cate').on('click', function (e) {
                e.preventDefault();
                _this.selectCate(e);
            });

            //编辑器
            $('[name="details"]').ckeditor();
            $('#intro').ckeditor({toolbar: []});
        },

        /**
         * edit by hp
         * @param uri
         */
        callback: function (uri) {
            if (uri) {
                window.location.href = uri;
            }
        },

        //验证市场价小于121价，暂时先放在这里吧
        validation: function (name) {
            if (name == 'market_price') {
                var price = typeof this.formData.price === 'undefined' ? this.model.get_data('price') : this.formData.price;
                var dom = $('[name="' + name + '"]');
                if (this.formData['market_price'] == '' || this.formData['market_price'] < price) {
                    if (dom.parent().hasClass('has-error')) {
                        return;
                    }
                    dom.parent().addClass('has-error').append('<span class="label label-warning error-msg">' + dom.attr('data-error-msg') + '</span>');
                } else {
                    dom.parent().removeClass('has-error').find('.error-msg').remove();
                }
            }
        },
        change: function (e) {
            this.formData[$(e.target).attr('name')] = $(e.target).val();
            this.validation($(e.target).attr('name'));
        },

        getChild: function (id) {
            if (typeof id === 'object') id = id[0];
            var child = [];
            for (var n in this.category) {
                if (id == this.category[n].id) {
                    child = this.category[n].child;
                    break;
                }
            }
            return child;
        },

        //选择分类
        selectCate: function (e) {
            var _this = this;
            if (typeof _this.model.data.cate_ids == 'undefined') {
                _this.model.data.cate_ids = [];
            }
            //一级分类
            _this.cate_form = $(template('cate-tpl', {}));
            $.each(_this.category, function (n, v) {
                _this.cate_form.find('[name="cate"]').append('<option value="' + v.id + '">' + v.name + '</option>');
            });
            //显示二级分类，并联动
            //bind change event
            _this.cate_form.find('[name="cate"]').on('change', function () {
                _this.cate_form.find('[name="child-cate"]').html('');
                var child = _this.getChild($(this).val());
                $.each(child, function (n, v) {
                    _this.cate_form.find('[name="child-cate"]').append('<option value="' + v.id + '">' + v.name + '</option>');
                });
            });
            //显示弹框
            _this.dialog = dialog({
                content: _this.cate_form,
                width: 400,
                ok: function () {
                    $.each(_this.cate_form.find('select[name="child-cate"]')[0].selectedOptions, function (n, option) {
                        if (_this.model.data.cate_ids.indexOf(option.value) >= 0) {
                            return false;
                        }
                        _this.cate.add(option.value, option.text);
                    });
                    _this.cate_form.remove();
                }, cancel: function () {
                }
            }).show(e.target);
        },

        //分类集合
        cate: {
            spec: this.spec_key,
            default: {
                deleted: false,
                init: function () {
                    this.event();
                    $('#cate-name').append(this.el);
                },
                event: function () {
                    var _this = this;
                    this.el.on('click', 'a', function (e) {
                        e.preventDefault();
                        _this.el.remove();
                        _this.deleted = true;
                        //var sid = $(this).parents().attr('id');
                        var cids = new Array();
                        $('#cate-name').children().each(function () {
                            cids.push($(this).attr('id'));
                        })

                        $.ajax({
                            url: _global.url.api + 'remove_specification',
                            data: {cid: cids, isGroup: false},
                            type: 'post',
                            dataType: 'json',
                            async: false,
                            success: function (res) {
                                if (res.code == 0) {
                                    var sids = eval(res.data);
                                    var sidsArr = new Array();
                                    for (var i in sids) {
                                        sidsArr[i] = 'spec' + sids[i];
                                    }
                                    var sidsLabel = new Array();
                                    $('#myspecification').children('label').each(function () {
                                        var re = $.inArray($(this).attr('id'), sidsArr);
                                        if (re < 0) {
                                            $(this).next('br').remove();
                                            $(this).remove();
                                        }
                                    })
                                }
                            }
                        });
                    });
                },
                del: function () {

                }
            },
            collection: [],
            add: function (id, name) {
                var el = $('<span class="label label-info mr10" id="' + id + '">' + name +
                ' <a href="" style="color: #fff"><span class="glyphicon glyphicon-remove"></span></a></span>');
                this.collection.push($.extend({el: el, id: id, name: name}, this.default));
                this.collection[this.collection.length - 1].init();
            },
            get: function () {
                var cate_ids = [];
                $.each(this.collection, function () {
                    !this.deleted && cate_ids.push(this.id);
                });
                return cate_ids;
            }
        }
    };

    new index();

});